package com.qiyuesuo.server.servlet;

import com.qiyuesuo.server.PO.FileInfo;
import com.qiyuesuo.server.dao.FileInfoDao;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URLEncoder;

/**
 * 下载文件
 * 按照文件名，从数据库获取文件位置，响应输出流写出文件
 * 加密数字信封，client端解密
 *
 * @author s77
 * @create 2020-4月-01 14:51
 */
public class DownloadServlet extends HttpServlet {
    private final static Logger logger = LoggerFactory.getLogger(DownloadServlet.class);

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) {
        try {
            //按文件名从数据库读取文件信息
            String name = request.getParameter("fileName");
            logger.info(name + " --从数据库读取文件信息");
            FileInfoDao dao = new FileInfoDao();
            FileInfo fileInfo = dao.select(name);
            //获取实际文件位置
            String path = fileInfo.getDirectoryAddress() + "/" + fileInfo.getName();
            String filename = fileInfo.getOriginalName();
            File f = new File(path);
            if (f.exists()) {
                //设置响应消息头，下载文件，文件名称，数字信封
                response.setCharacterEncoding("utf-8");
                response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(filename) + "");
                response.addHeader("digitalEnvelope", fileInfo.getDigitalEnvelope());
                logger.info(name + " -- 读取文件内容");
                FileInputStream fis = new FileInputStream(f);
                //获取响应报文输出流对象
                ServletOutputStream out = response.getOutputStream();
                byte[] b = new byte[1024];
                int len = -1;
                while ((len = fis.read(b)) != -1) {
                    out.write(b, 0, len);
                    out.flush();
                }
                out.flush();
                out.close();
                fis.close();
            } else {
                logger.error(name + " -- 文件不存在");
                throw new FileNotFoundException();
            }
        } catch (Exception e) {
            logger.error("下载文件失败", e);
            response.setContentType("text/html");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            try {
                response.getWriter().println("<h1>401</h1>");
            } catch (IOException ex) {
                ex.printStackTrace();
            }

        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
}
